package top.roadvast.pdshopping.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
import top.roadvast.pdshopping.bean.PdLog;
import top.roadvast.pdshopping.service.LogService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 20:50
 * @Version 1.0
 * @Description rabbitmq监听器
 * 收到日志数据后,会调用日志的业务代码,把日志保存到数据库
 */
@Component
@Slf4j
//将队列和交换机通过bindingKey绑定
//注意：交换机和队列的绑定关系一旦建立，要想解除绑定需要到rabbitmq控制台解除
//所以消费者01和02的队列名称不能相同
//消费者01
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "pd_log_direct_queue01"),
        exchange = @Exchange(value = "pd_log_direct_exchange", type = ExchangeTypes.DIRECT, durable = "true"),
        key = {"info", "error"}))
//消费者02
//@RabbitListener(bindings = {@QueueBinding(
//        value = @Queue(value = "pd_log_direct_queue02"),
//        exchange = @Exchange(value = "pd_log_direct_exchange", type = ExchangeTypes.DIRECT, durable = "true"),
//        key = "warning")}
//)
public class DirectLogConsumer {
    @Resource
    LogService logService;

    /**
     * rabbitmq六种工作模式之一：直连模式
     * 消费者01和消费者02通过bindingKey接收数据
     * 收到消息后会把数据转为 PdLog 实例传递到此方法
     */
    @RabbitHandler
    public void save(PdLog pdLog, Channel channel, Message message) {
        try {
            log.info("接收到日志，开始进行处理...");
            log.info("订单信息：" + pdLog);
            logService.saveLog(pdLog);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
